<template>
  <div class="app-container flex column">
    <top-title :policeView="true" :cusString="cusString"></top-title>
    <div class="content-wrap f1 flex column">
      <!-- 搜索栏 -->
      <div class="search-group">
        <div class="input-wrap">
          <div class="label">民警姓名:</div>
          <div class="input-item">
            <a-input :maxLength="30" clearable v-model="queryParam.policeUserName" placeholder="请输入民警姓名" />
          </div>
        </div>

        <div class="input-wrap">
          <div class="label">民警警号:</div>
          <div class="input-item">
            <a-input :maxLength="30" clearable v-model="queryParam.policeUserNo" placeholder="请输入民警警号" />
          </div>
        </div>

        <div class="input-wrap">
          <div class="label">提交时间:</div>
          <div class="input-item">
            <a-month-picker
              v-model="queryParam.value"
              :disabled-date="disabledDate"
              :allowClear="false"
              @change="timeChange"
              value-format="YYYY-MM"
            />
          </div>
        </div>

        <div class="btn-wrap">
          <a-button class="searchBtn" @click="searchQuery()" type="primary"> 搜索 </a-button>
          <a-button class="resetBtn" @click="searchReset()" type="primary"> 重置 </a-button>
        </div>

        <div class="btn-group">
          <a-button
            class="exportBtn"
            @click="handleExportXls(`${cusString}`, { startTime: queryParam.startTime, endTime: queryParam.endTime })"
            type="primary"
          >
            导出Excel
          </a-button>
        </div>
      </div>

      <div class="table-wrap f1">
        <a-table
          bordered
          class="tableList"
          id="a-table"
          ref="exportTableRef"
          :scroll="{ x: 999 }"
          rowKey="policeUserNo"
          :columns="cusColumns"
          :dataSource="dataSource"
          :pagination="ipagination"
          @change="handleTableChange"
        >
        </a-table>
      </div>
    </div>
  </div>
</template>

<script>
import XLSX from 'xlsx'
import fs from 'file-saver'
import topTitle from '@/components/topTitle'
import startEndTime from '@/components/startEndTime'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction } from '@/api/manage'
export default {
  name: 'policeInspector',
  components: { topTitle, startEndTime },
  mixins: [JeecgListMixin],
  data() {
    return {
      cusString: '',
      url: {
        list: '/police/staion/directorOfAnInstitute/page',
        exportXlsUrl: '/police/staion/directorOfAnInstitute/page/export',
      },
      disableMixinCreated: true,
      columns: [
        {
          title: '序号',
          align: 'center',
          width: 100,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '民警姓名',
          width: 150,
          ellipsis: true,
          align: 'center',
          dataIndex: 'policeUserName',
        },
        {
          title: '总分',
          width: 150,
          ellipsis: true,
          align: 'center',
          dataIndex: 'totalScore',
        },
        // {
        //   title: '警号',
        //   dataIndex: 'policeUserNo',
        //   ellipsis: true,
        //   width: 150,
        //   align: 'center',
        // },
      ],
      curMonth: '',
      cusColumns: [],
    }
  },
  mounted() {
    this.queryParam.value = this.$moment().format('YYYY-MM')
    this.timeChange()
    this.loadData()
  },
  methods: {
    disabledDate(current) {
      return current && current > this.$moment().endOf('day')
    },
    timeChange(v, index) {
      this.$forceUpdate()
      this.queryParam.startTime = this.$moment(this.queryParam.value).startOf('month').valueOf()
      this.queryParam.endTime = this.$moment(this.queryParam.value).endOf('month').valueOf()
    },

    customCell(record, rowIndex, column) {
      // column add from 3.0
      let _this = this
      return {
        on: {
          click: (event) => {
            // 当前点击的单元格
            // console.log(event, 'event')
            let value = this.queryParam.value
            let policeUserId = record.policeUserId
            let policeUserName = record.policeUserName
            let policeAgencyName = record.policeAgencyName
            let dataIndex = event.target.__vue__.column.dataIndex
            if (dataIndex == 'totalScore' || dataIndex == 'policeUserName') {
              let params = { policeUserId, policeUserName, policeAgencyName, value }
              // console.log(dataIndex, 'dataIndex')
              if (dataIndex == 'policeUserName') {
                this.$router.push({ path: '/policeInspector/policeDetail', query: params })
              } else {
                this.$router.push({ path: '/policeInspector/totalPoints', query: params })
              }
              return
            }
            let bizId = _this.getNodeByName(_this.cusColumns, dataIndex).bizId
            let { title } = _this.cusColumns.filter((item) => {
              if (bizId.includes(item.bizId)) {
                return item
              }
            })[0]
            if (policeUserId && dataIndex && bizId) {
              let params = { policeUserId, bizId, policeUserName, policeAgencyName, title, value }
              if (dataIndex.includes('Sum')) {
                params.isShowCheckResult = true
                params.type = '检查总数'
                this.$router.push({ path: '/policeInspector/detail', query: params })
              } else if (dataIndex.includes('unqualified')) {
                params.type = '不合格'
                this.$router.push({ path: '/policeInspector/unDetail', query: params })
              } else if (dataIndex.includes('penalties')) {
                params.type = '责令整改通知书'
                this.$router.push({ path: '/policeInspector/penaltiesDetail', query: params })
              } else {
                params.type = '合格数'
                params.checkResult = 1
                params.isShowCheckResult = false
                this.$router.push({ path: '/policeInspector/detail', query: params })
              }
            } else {
              this.$message.warning('此处不可跳转')
            }
          },
        },
      }
    },

    searchReset() {
      this.queryParam = {}
      this.queryParam.value = this.$moment().format('YYYY-MM')
      this.timeChange()
      this.loadData()
    },
    async loadData() {
      this.queryParam.pageNo = this.ipagination.current
      this.queryParam.pageSize = this.ipagination.pageSize
      let { result } = await getAction(this.url.list, this.queryParam)
      this.cusColumns = this.columns.concat(result.keyName)
      this.allChildrenAddValue(this.cusColumns) //递归塞值
      this.dataSource = result.page.records
      this.ipagination.total = result.page.total

      this.curMonth = this.queryParam.value.split('-')[1]
      this.cusString = `${JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value.policeAgencyName}下民警${
        this.curMonth
      }月场所检查情况统计表`
    },

    allChildrenAddValue(node) {
      for (const item of node) {
        if (item.title && item.title !== '序号' && !item.children) {
          item.width = 100
          item.align = 'center'
          item.customCell = this.customCell
        }
        if (item.children) {
          this.allChildrenAddValue(item.children)
        }
      }
      return node
    },

    getNodeByName(list, index) {
      for (const item of list) {
        if (item.dataIndex === index) return item
        if (item.children) {
          const res = this.getNodeByName(item.children, index)
          if (res) return res
        }
      }
    },

    getNodeById(list, id) {
      if (id == '') return { policeAgencyName: '暂无' }
      for (const item of list) {
        if (item.id === id) return item
        if (item.children) {
          const res = this.getNodeById(item.children, id)
          if (res) return res
        }
      }
    },

    // 导出当前页
    exportExcel() {
      const wb = XLSX.utils.table_to_book(document.querySelector('#a-table'))

      const wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array',
      })
      try {
        fs.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '检查数据.xlsx')
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
    },
  },
  destroy() {},
}
</script>

<style scoped lang="less">
/deep/ .ant-table-body {
  border: 1px solid #0a5297 !important;
  .ant-table-thead > tr > th,
  .ant-table-tbody > tr > td {
    border: 1px solid #0a5297 !important;
  }

  .ant-table-tbody {
    cursor: pointer;
  }
}

/deep/ .ant-table-row-cell-break-word:hover {
  background: #1388ff !important;
  // cursor: pointer;
}

.app-container {
  background: var(--theme-content-bg);
  padding-top: 0;
  padding-bottom: 0;
  .content-wrap {
    background: var(--theme-container-bg);
    overflow: hidden;
    .table-wrap {
      padding: 0 20px;
      overflow: auto;
    }
  }
}
</style>
